//
//  so_user.swift
//  XPApp
//
//  Created by zhuxietong on 2017/2/13.
//  Copyright © 2017年 zhuxietong. All rights reserved.
//

import Foundation
import Eelay
import UIKit
import RxSwift

extension JoUser
{
    public enum Notice:String,NotifyType {
        
        case changeUserInfo = "changeUserInfo"
        case login = "login"
        case logout = "logout"
        
        public var name: Notification.Name{
            switch self {
            case .changeUserInfo:
                return "JoUser.changeUserInfo".notice_name
            case .login:
                return "JoUser.login".notice_name
            default:
                return "JoUser.logout".notice_name
            }
//            return "JoUser.\(Notice.self)\(self.rawValue)".notice_name
        }
    }
    
}


extension JoUser
{
    public static var token_node = "token"
    public static var id_node = "id"
    
    public enum Event {
        case login(JoUser)
        case logout
        case update(info:NSMutableDictionary)
    }
    
    public static var event:PublishSubject<Event> = PublishSubject<Event>()
    
  
}

public class JoUser:NSObject {
    
    public static var __db:DB.sqlite? = DB.sqlite(db_name: "user.db",bundle:Bundle(for: JoUser.self))
    
    public var userid:String = ""
    public var token:String = ""
    public var online:String = "NO"
    
    public static var bindPushTokenBlock:()->Void = {}
    public static var unBindPushTokenBlock:()->Void = {}
    
    

    
    public var json:String{
        set{
            let str = newValue.replacingOccurrences(of: "````", with: "'")
            info = str.JsonDictionary ?? NSMutableDictionary()
            self.userid = info[JoUser.id_node,userid]
            self.token = info[JoUser.token_node,token]
        }
        get{
            let js = info.rawJson ?? "{}"
            return js.replacingOccurrences(of: "'", with: "````")
        }
    }
    public static var syncKeys = ["name","gender","nickname","birthday","avatar","mobile"]
    public static var setInfo:(_:NSMutableDictionary,_:JoUser)->Void = {
        info,user in
        info.startSync(scheme: .init(keys: JoUser.syncKeys, primaryKey: "id", table: "JoUser"))
    }
    
    
    public var info:NSMutableDictionary = NSMutableDictionary()
    {
        didSet{
            self.userid = info[JoUser.id_node,userid]
            self.token = info[JoUser.token_node,token]
            JoUser.setInfo(info,self)
        }
    }
    
    
     public func save() {
        let time = Date()["STAMP"]
        if  JoUser.db.query(sql: "select * from user where id = '\(userid)'").count > 0{
            let sql = "update user set token = '\(token)', json = '\(json)', time = '\(time)', online = '\(online)' where id = '\(self.userid)'"
            //                debugPrint("pppooo:\(sql)")
            JoUser.db.exec(sql: sql)
        }
        else{
            //                debugPrint("insert:\(sql)")
            let sql = "insert into user(id,token,json,online,time) values('\(self.userid)','\(self.token)','\(self.json)','\(self.online)','\(time)')"

            JoUser.db.exec(sql: sql)
        }
        JoUser.event.onNext(.update(info: info))
        __post(notify: Notice.changeUserInfo)
        
    }
    
    public func login() {
        let users = JoUser.users
        for one in users{
            if one.userid != self.userid
            {
                let sql = "update user set online = 'NO' where id = '\(one.userid)'"
                JoUser.db.exec(sql: sql)
            }
        }
        self.online = "YES"
        JoUser.__loginUser = self
        self.save()
        self.bindDeviceToken()
        __post(notify: Notice.login)
        JoUser.event.onNext(.login(self))
        print("------login in")

    }
    
    public func loginOut() {
        self.online = "NO"

        self.save()
        JoUser.__loginUser = nil
        unbindDeviceToken()
        __post(notify: Notice.logout)
        JoUser.event.onNext(.logout)

        print("------login out")

       
    }
    
    
    
    public class var users:[JoUser]{
        var us = [JoUser]()
        let data = JoUser.db
        let ls = data.query(sql: "select * from user order by -time")
        for one in ls{
            let u = JoUser()
            if let id = one["id"] as? String
            {
                u.userid = id
            }
            if let token = one["token"] as? String
            {
                u.token = token
            }
            if let json = one["json"] as? String
            {
                u.json = json
            }
            if let online = one["online"] as? String
            {
                u.online = online
            }
            us.append(u)
        }
        return us
    }
    
    
    
    public class func currentUser()->JoUser?{
        let us = JoUser.users
        if us.count > 0{
            let u = us[0]
            print("aklsdflasdf---",u.info)

            return u
        }
        return nil
    }
    
    static var __loginUser:JoUser?
    
    class func __loginUser__()->JoUser?{
        guard let u = JoUser.currentUser() else{return nil}
        if u.online == "YES"{
            JoUser.__loginUser = u
            return u
        }
        return nil
    }
    
    
    public class func loginUser()->JoUser?{
        if let user = JoUser.__loginUser
        {
            return user
        }
        else{
            let u = JoUser.__loginUser__()
            return u
        }
    }
    
    
    public static var db:DB.sqlite{
        guard let d = JoUser.__db else {
            let data = DB.sqlite(db_name: "user.db")
            JoUser.__db = data
            return data
        }
        return d
    }
    
    public func bindDeviceToken() {
        JoUser.bindPushTokenBlock()
    }
    
    public func unbindDeviceToken() {
        JoUser.unBindPushTokenBlock()
    }
}

extension JoUser
{
    var userType:String{
        get{
            return info["type","个人".loc]
        }
    }
    var headImg:String{
        get{
            return info["headimg",""]
        }
    }
    
    var userName:String{
        get{
            
            var username = info["username",""]
            if username == ""
            {
                username = info["nickname",""]
            }
            if username == ""
            {
                username = info["phone",""]
            }
            
            return username
        }
    }

    var nickName:String{
        get{
            
            var username = info["nickname",""]
            if username == ""
            {
                username = info["username",""]
            }
            if username == ""
            {
                username = info["phone",""]
            }
            
            
            return username
        }
    }
    
    static var msgOnwner:String{
        get{
            return JoUser.loginUser()?.userid ?? "XX"
        }
    }
    
    var dichanName:String{
        get{
            return info["estatename",""]
        }
    }
    
    
}




extension JoUser{
    public static func authAction(message:String="登录后进行相关操作".loc,at:UIViewController?=nil,action:(_:JoUser)->Void){
        if let u = JoUser.loginUser(){
            action(u)
        }
        else{
            var ctr = at
            if ctr == nil{
                ctr = __controller
            }
            JoAlertView(info: "提示".loc,message).append(title: "取消".loc, style: .cancel) {
                }.append(title: "登录".loc, style: .default) {
                    EeAuthControl.getUser(finish_block: { (success, msg, user) in
                        
                    })
                }.show(at: ctr)
        }
    }
}
